﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace UIFrameWork
{
    public class GeneratorFindComponentTool : Editor
    {
        public static Dictionary<int, string> objFindPathDic;
        public static List<EditorObjectData> objDataList;

        [MenuItem("GameObject/Farmework/UGUI/生成组件查找脚本(Shift+U) #U", false, 0)]
        private static void CreaterFindComponentScripts()
        {
            GameObject obj = Selection.objects.First() as GameObject;
            if (obj == null)
            {
                Debug.LogError("需要选择 GameObject");
                return;
            }

            if (Directory.Exists(GeneratorConfig.FindComponentGenertorPath))
            {
                Directory.CreateDirectory(GeneratorConfig.FindComponentGenertorPath);
            }
            objDataList = new List<EditorObjectData>();
            objFindPathDic = new Dictionary<int, string>();
            PresWindowNodeData(obj.transform, obj.name);
            if (GeneratorConfig.ParseType == ParseType.Tag)
                PresWindowNodeDataByTag(obj.transform, obj.name);
            else
                PresWindowNodeData(obj.transform, obj.name);
            // 储存字段名称
            //string datalistJson = JsonConvert.SerializeObject(objDataList);
            //PlayerPrefs.SetString(GeneratorConfig.OBJDATALIST_KEY, datalistJson);
            // 生成脚本
            string cs = CreateCS(obj.name);
            string csPath = GeneratorConfig.FindComponentGenertorPath + "/" + obj.name + "UIComponent.cs";
            //Debug.Log(csPath);
            UIWindowEditor.ShowWindow(cs, csPath);
        }
        /// <summary>
        ///  解析窗口节点数据
        /// </summary>
        /// <param name="trans"></param>
        /// <param name="winName"></param>
        public static List<EditorObjectData> PresWindowNodeData(Transform trans, string winName)
        {
            for (int i = 0; i < trans.childCount; i++)
            {
                var obj = trans.GetChild(i).gameObject;
                string name = obj.name;
                if (name.Contains("[") && name.Contains("]"))
                {
                    int index = name.IndexOf("]") + 1;
                    string fieldName = name.Substring(index, name.Length - index);
                    string fieldType = name.Substring(1, index - 2);

                    objDataList.Add(new EditorObjectData { fieldName = fieldName, fieldType = fieldType, insID = obj.GetInstanceID() });

                    // 计算该节点的查找路径
                    string objPath = name;
                    bool isFindOver = false;
                    Transform parent = obj.transform;
                    for (int k = 0; k < 20; k++)
                    {
                        for (int j = 0; j <= k; j++)
                        {
                            if (k == j)
                            {
                                parent = parent.parent;
                                // 如果父节点是当前窗口，说明查找已经结束
                                if (string.Equals(parent.name, winName))
                                {
                                    isFindOver = true;
                                    break;
                                }
                                else
                                {
                                    objPath = objPath.Insert(0, parent.name + "/");
                                }
                            }
                        }
                        if (isFindOver)
                        {
                            break;
                        }
                    }
                    objFindPathDic.Add(obj.GetInstanceID(), objPath);
                }
                PresWindowNodeData(trans.GetChild(i), winName);
            }

            return objDataList;
        }

        public static List<EditorObjectData> PresWindowNodeDataByTag(Transform trans, string winName)
        {
            for (int i = 0; i < trans.childCount; i++)
            {
                var obj = trans.GetChild(i).gameObject;
                string tagName = obj.tag;
                string name = obj.name;
                if (GeneratorConfig.TAGArr.Contains(tagName))
                {
                    string fieldName = obj.name;//获取字段昵称
                    string fieldType = tagName;//获取字段类型

                    objDataList.Add(new EditorObjectData { fieldName = fieldName, fieldType = fieldType, insID = obj.GetInstanceID() });

                    // 计算该节点的查找路径
                    string objPath = name;
                    bool isFindOver = false;
                    Transform parent = obj.transform;
                    for (int k = 0; k < 20; k++)
                    {
                        for (int j = 0; j <= k; j++)
                        {
                            if (k == j)
                            {
                                parent = parent.parent;
                                // 如果父节点是当前窗口，说明查找已经结束
                                if (string.Equals(parent.name, winName))
                                {
                                    isFindOver = true;
                                    break;
                                }
                                else
                                {
                                    objPath = objPath.Insert(0, parent.name + "/");
                                }
                            }
                        }
                        if (isFindOver)
                        {
                            break;
                        }
                    }
                    objFindPathDic.Add(obj.GetInstanceID(), objPath);
                }
                PresWindowNodeDataByTag(trans.GetChild(i), winName);
            }

            return objDataList;
        }

        public static string CreateCS(string name)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("/*----------------------------------");
            sb.AppendLine(" *Title:UI自动化组件查找代码生成工具");
            sb.AppendLine(" *Author:SteveSimon");
            sb.AppendLine(" *Date:" + System.DateTime.Now);
            sb.AppendLine(" *Description:变量需以[Text]括号加组件的类型的格式进行声明，然后右键窗口节点一键生成UI组件查找脚本即可");
            sb.AppendLine(" *注意*:以下脚本是自动生成的，每次更新都会覆盖，请不要手动修改");
            sb.AppendLine(" *----------------------------------*/");
            sb.AppendLine();

            sb.AppendLine("using UnityEngine.UI;");
            sb.AppendLine("using UnityEngine;");
            sb.AppendLine("using UIFrameWork.UGUIPro;");
            sb.AppendLine();

            sb.AppendLine("namespace UIFrameWork");
            sb.AppendLine("{");

            sb.AppendLine("\tpublic class " + name + "UIComponent");
            sb.AppendLine("\t{");

            foreach (var item in objDataList)
            {
                sb.AppendLine("\t\tpublic " + item.fieldType + " " + item.fieldName + item.fieldType + ";\n");
            }

            sb.AppendLine("\t\tpublic void InitComponent(WindowBase target)");
            sb.AppendLine("\t\t{");
            foreach (var item in objFindPathDic)
            {
                var itemData = GetEditorObjectData(item.Key);
                string relFieldName = itemData.fieldName + itemData.fieldType;
                if (string.Equals("GameObject", itemData.fieldType))
                {
                    sb.AppendLine($"\t\t\t{relFieldName} = target.transform.Find(\"{item.Value}\").gameObject;");
                }
                else if (string.Equals("Transform", itemData.fieldType))
                {
                    sb.AppendLine($"\t\t\t{relFieldName} = target.transform.Find(\"{item.Value}\").transform;");
                }
                else
                {
                    sb.AppendLine($"\t\t\t{relFieldName} = target.transform.Find(\"{item.Value}\").GetComponent<{itemData.fieldType}>();");
                }
            }

            sb.AppendLine();
            sb.AppendLine($"\t\t\t{name} _window = ({name})target;");
            foreach (var item in objDataList)
            {
                string type = item.fieldType;
                string methodName = item.fieldName;
                string suffix = "";
                if (type.Contains("Button"))
                {
                    suffix = "Click";
                    sb.AppendLine($"\t\t\ttarget.AddButtonClickListener({methodName}{type}, _window.On{methodName}Button{suffix});");
                }
                if (type.Contains("IputField"))
                {
                    sb.AppendLine($"\t\t\ttarget.AddInputFieldListener({methodName}{type}, _window.On{methodName}InputChage, _window.On{methodName}InputEnd);");
                }
                if (type.Contains("Toggle"))
                {
                    suffix = "Change";
                    sb.AppendLine($"\t\t\ttarget.AddToggleClickListener({methodName}{type}, _window.On{methodName}Toggle{suffix});");
                }
            }
            sb.AppendLine("\t\t}");
            sb.AppendLine("\t}");
            sb.AppendLine("}");
            sb.AppendLine();
            return sb.ToString();
        }

        public static EditorObjectData GetEditorObjectData(int insid)
        {
            foreach (var item in objDataList)
            {
                if (item.insID == insid)
                {
                    return item;
                }
            }
            return null;
        }
    }

    public class EditorObjectData
    {
        public int insID;
        public string fieldName;
        public string fieldType;
    }
}
